<template>

 
<div class="register-box">
        
  <el-form ref="registerFormRef" :model="formData" :rules="registerRules">
    
    <!-- 邮箱显示区域 -->
  
    <el-form-item prop="verificationCode" label="確認コード">
      <el-input v-model="formData.verificationCode"  class="verification-input" style="width: 30.5%;height: 32px;">
      </el-input>
    </el-form-item>
    
    <el-form-item prop="username" label="ユーザー名">
      <el-input v-model="formData.username"  class="username-input"style="width: 30.5%;height: 32px;">

      </el-input>
      <div class="form-desc">※ユーザー名は登録時に変更できません。表示名はプロフィール編集画面でいつでも設定できます。</div>
      <div class="form-tip">※半角英数字4～16文字</div>
    </el-form-item>
    
    <el-form-item prop="password" label="パスワード">
      <div class="input-with-tip">
        <el-input v-model="formData.password" type="password" show-password class="password-input" style="width: 30.5%;height: 32px;">
        </el-input>
        <div class="form-tip">※半角英数字8～12文字、記号利用可能</div>
      </div>
    </el-form-item>
    
    <el-form-item prop="repassword" label="パスワードを再入力してください">
      <el-input v-model="formData.repassword" type="password" show-password class="password-confirm-input"style="width: 30.5%;height: 32px;">
      </el-input>
    </el-form-item>
    
    <el-form-item prop="type">
      <el-radio-group v-model="formData.type" class="user-type-radio">
        <el-radio :label="1">個人</el-radio>
        <el-radio :label="2">法人</el-radio>
      </el-radio-group>
    </el-form-item>
    
    <div class="name-group">
      <el-form-item prop="surname" class="half-width" label="氏名（姓）">
        <el-input v-model="formData.surname" class="name-input" style="width: 200px;height: 32px;"></el-input>
      </el-form-item>
      <el-form-item prop="name" class="half-width" label="（名）">
        <el-input v-model="formData.name" class="name-input" style="width: 200px;height: 32px;"></el-input>
      </el-form-item>
    </div>
    
    <div class="name-group">
      <el-form-item prop="surname2" class="half-width" label="氏名（ひらがな）">
        <el-input v-model="formData.surname2" class="name-input" style="width: 200px;height: 32px;"></el-input>
      </el-form-item>
      <el-form-item prop="name2" class="half-width" label="（ひらがな）">
        <el-input v-model="formData.name2" class="name-input" style="width: 200px;height: 32px;"></el-input>
      </el-form-item>
    </div>
    
    <!-- 公司相关字段，仅在用户类型为法人时显示 -->
    <div v-if="formData.type === 2">
      <el-form-item prop="company_name" label="公司名称">
        <el-input v-model="formData.company_name" class="company-input" style="width: 30.5%;height: 32px;">
        </el-input>
      </el-form-item>
      <div class="company-group">
        <el-form-item prop="company_number" class="half-width" label="公司编号">
          <el-input v-model="formData.company_number"  style="width: 200px;height: 32px;"></el-input>
        </el-form-item>
        <el-form-item prop="company_phone" class="half-width" label="电话号码">
          <el-input v-model="formData.company_phone"  style="width: 200px;height: 32px;"></el-input>
        </el-form-item>
      </div>
    </div>
    
    <el-form-item prop="address" label="住所（番地まで）">
      <el-input v-model="formData.address" type="textarea" :rows="1" class="address-input" style="width: 30.5%;height: 32px;"></el-input>
    </el-form-item>
    
    <el-form-item prop="zip_code" label="郵便番号">
      <el-input v-model="formData.zip_code"  class="zip-input" style="width: 30.5%;height: 32px;"></el-input>
    </el-form-item>
    
    <el-form-item prop="prefectures" label="都道府県">
      <el-input v-model="formData.prefectures"  class="prefecture-input" style="width: 30.5%;height: 32px;"></el-input>
    </el-form-item>

    <el-form-item prop="agreeTerms" style="margin-bottom: 15px;">
      <div class="checkbox-container">
        <el-checkbox v-model="formData.agreeTerms"><a href="/article/3" class="terms-link">利用規約</a>および<a href="/article/2" class="terms-link">個人情報の取り扱い</a>について同意します。</el-checkbox>
      </div>
    </el-form-item>
    <el-form-item>
      <div class="button-container">
        <el-button type="primary" class="register-button" style="width: 175.5px;height: 32px;" @click="handleSubmit"><span style="font-size: 14px;">入力内容を確認する</span></el-button>
      </div>
    </el-form-item>
  </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Message, Lock, Key, User, OfficeBuilding } from '@element-plus/icons-vue'
import { userApi } from '../api/index'

// 定义props
const props = defineProps({
  email: {
    type: String,
    required: true
  },
  modelValue: {
    type: Object,
    default: () => ({
      verificationCode: '',
      username: '',
      password: '',
      repassword: '',
      type: 1,
      surname: '',
      name: '',
      surname2: '',
      name2: '',
      address: '',
      zip_code: '',
      prefectures: '',
      company_name: '',
      company_number: '',
      company_phone: '',
      agreeTerms: false
    })
  }
})

// 定义emits
const emit = defineEmits(['update:modelValue', 'submit', 'changeEmail'])

// 初始化路由
const router = useRouter()

// 表单引用
const registerFormRef = ref(null)

// 表单数据
const formData = reactive({ ...props.modelValue })

// 监听表单数据变化，同步到父组件
const updateFormData = () => {
  emit('update:modelValue', { ...formData })
}

// 监听用户类型变化，重置公司相关字段
watch(() => formData.type, (newType) => {
  if (newType === 1) {
    formData.company_name = ''
    formData.company_number = ''
    formData.company_phone = ''
  }
  updateFormData()
})

// 注册表单验证规则
const registerRules = {
  // verificationCode: [
  //   { required: true, message: '请输入バリデーションコード', trigger: 'submit' },
  //   { min: 6, max: 6, message: 'バリデーションコードの長さは6文字でなければなりません', trigger: 'submit' }
  // ],
  // username: [
  //   { required: true, message: 'ユーザー名を入力してください', trigger: 'blur' },
  //   { min: 3, message: 'ユーザー名の長さは3文字以上でなければなりません', trigger: 'blur' }
  // ],
  // password: [
  //   { required: true, message: 'パスワードを入力してください', trigger: 'blur' },
  //   { min: 6, message: 'パスワードの長さは6文字以上でなければなりません', trigger: 'blur' }
  // ],
  // repassword: [
  //   { required: true, message: 'パスワードを再入力してください', trigger: 'blur' },
  //   {
  //     validator: (rule, value, callback) => {
  //       if (value !== formData.password) {
  //         callback(new Error('パスワードが一致しません'))
  //       } else {
  //         callback()
  //       }
  //     },
  //     trigger: 'blur'
  //   }
  // ],
  // type: [
  //   { required: true, message: 'ユーザータイプを選択してください', trigger: 'change' }
  // ],
  // surname: [
  //   { required: true, message: '姓を入力してください', trigger: 'blur' }
  // ],
  // name: [
  //   { required: true, message: '名を入力してください', trigger: 'blur' }
  // ],
  // surname2: [
  //   { required: true, message: '姓を入力してください', trigger: 'blur' }
  // ],
  // name2: [
  //   { required: true, message: '名を入力してください', trigger: 'blur' }
  // ],
  // address: [
  //   { required: true, message: '住所を入力してください', trigger: 'blur' }
  // ],
  // zip_code: [
  //   { required: true, message: '郵便番号を入力してください', trigger: 'blur' }
  // ],
  // prefectures: [
  //   { required: true, message: '都道府県を入力してください', trigger: 'blur' }
  // ],
  // company_name: [
  //   { 
  //     required: false, 
  //     validator: (rule, value, callback) => {
  //       if (formData.type === 2 && !value) {
  //         callback(new Error('会社名を入力してください'))
  //       } else {
  //         callback()
  //       }
  //     },
  //     trigger: 'blur' 
  //   }
  // ],
  // company_number: [
  //   { 
  //     required: false, 
  //     validator: (rule, value, callback) => {
  //       if (formData.type === 2 && !value) {
  //         callback(new Error('会社番号を入力してください'))
  //       } else {
  //         callback()
  //       }
  //     },
  //     trigger: 'blur' 
  //   }
  // ],
  // company_phone: [
  //   { 
  //     required: false, 
  //     validator: (rule, value, callback) => {
  //       if (formData.type === 2 && !value) {
  //         callback(new Error('会社電話を入力してください'))
  //       } else {
  //         callback()
  //       }
  //     },
  //     trigger: 'blur' 
  //   }
  // ],
  // agreeTerms: [
  //   {
  //     validator: (rule, value, callback) => {
  //       if (!value) {
  //         // callback(new Error('サービス利用規約を読み、同意してください'))
  //       } else {
  //         callback()
  //       }
  //     },
  //     trigger: 'change'
  //   }
  // ]
}

// 处理提交
const handleSubmit = () => {
  registerFormRef.value.validate((valid) => {
    if (valid) {
      // 构建注册数据
      const registrationData = {
        code: formData.verificationCode,  //验证码
        username: formData.username,  //用户名
        password: formData.password,   //密码
        repassword: formData.repassword,  //确认密码
        email: props.email,    //邮箱
        type: formData.type,   //用户类型
        surname: formData.surname,    //姓
        name: formData.name,    //名字
        surname2: formData.surname2,  //假名
        name2: formData.name2,   //假名
        address: formData.address,   //地址
        zip_code: formData.zip_code,  //邮政编码
        prefectures: formData.prefectures,    //都道府県 
        company_name: formData.company_name,  //会社名
        company_number: formData.company_number,  //会社番号
        company_phone: formData.company_phone  //会社電話
      }
      // 调用后端API进行注册
      userApi.register(registrationData).then(res => {
        console.log(res)
        // 注册成功后跳转到登录页
        // router.push('/login')
        if(res.code == -1){
          ElMessage.error(res.msg)
        }else if(res.code == 1){
          ElMessage.success('登録が順調に完了しました')
          // 注册成功后跳转到登录页
          router.push('/login')
          // 关闭弹窗
        }
      }).catch(error => {
        ElMessage.error(error.message || '注册失败，请稍后重试')
      })
    }
  })
}

// 处理更改邮箱
const handleChangeEmail = () => {
  emit('changeEmail')
}

// 监听props变化
watch(() => props.modelValue, (newVal) => {
  Object.assign(formData, newVal)
}, { deep: true })

// 监听formData变化
watch(formData, updateFormData, { deep: true })
</script>

<style scoped>
.register-content .register-left {
  transition: all 0.3s ease;
}

.register-content .register-left:only-child,
.register-content .register-left:nth-last-child(1):first-child {
  flex: 1 1 100%;
  max-width: 100%;
}
.register-left {
  flex: 1;
  /* padding: 30px; */
  display: flex;
  flex-direction: column;
  background-color: transparent;
}
.logo {
  height: 60px;
  object-fit: contain;
}
.logo-container {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.logo-container a {
  display: inline-block;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.logo-container a:hover {
  transform: scale(1.05);
}
.register-title {
  text-align: center;
  margin-bottom: 25px;
  color: #333;
  font-size: 18px;
  font-weight: 500;
}
.register-box {
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-sizing: border-box;
}

/* 表单项通用样式 */
:deep(.el-form-item) {
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
}

:deep(.el-form-item__label) {
  display: flex !important;
  justify-content: flex-start !important;
  font-size: 12px;
  color: #333;
  font-weight: 500;
  line-height: 1.4;
  padding-bottom: 4px;
  width: 180px !important;
  text-align: left;
  flex-shrink: 0;
}

:deep(.el-form-item__content) {
  flex: 1;
  margin-left: 0 !important;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  padding: 6px 8px;
  min-height: 28px;
}

:deep(.el-input__inner) {
  font-size: 12px;
  color: #333;
}

:deep(.el-radio) {
  margin-right: 15px;
}

:deep(.el-radio__label) {
  font-size: 12px;
  color: #333;
}

:deep(.el-button) {
  font-size: 12px;
  padding: 8px 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-box {
    max-width: 100%;
    padding: 20px 15px;
    margin: 0 10px;
  }
  
  /* 移动端复选框容器 */
  .checkbox-container {
    margin-left: 0 !important;
    text-align: left;
  }
}

@media (max-width: 480px) {
  .register-box {
    padding: 15px 10px;
    margin: 0 5px;
  }
  
  /* 移动端复选框容器 */
  .checkbox-container {
    margin-left: 0 !important;
    text-align: left;
  }
}
/* 邮箱显示区域 */
.email-display {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 12px;
}

.email-display .el-icon {
  color: #909399;
  font-size: 14px;
}

.email-display span {
  flex: 1;
  color: #333;
}

.change-email-btn {
  font-size: 12px;
  padding: 0;
  color: #409eff;
}

/* 验证码输入框 */
:deep(.verification-input .el-input__wrapper) {
  width: 100%;
}

/* 用户名输入框 */
:deep(.username-input .el-input__wrapper) {
  width: 100%;
}

/* 密码输入框 */
:deep(.password-input .el-input__wrapper),
:deep(.password-confirm-input .el-input__wrapper) {
  width: 100%;
}

/* 用户类型选择 */
.user-type-radio {
  display: flex;
  gap: 20px;
  margin-left: 180px;
}

/* 姓名组布局 */
.name-group {
  display: flex;
  gap: 15px;
  margin-bottom: 12px;
  align-items: flex-start;
}

.name-group .half-width {
  flex: 1;
  margin-bottom: 0;
}

.name-group :deep(.el-form-item__label) {
  width: auto !important;
  min-width: 80px;
}

.name-group .half-width:first-child :deep(.el-form-item__label) {
  width: 180px !important;
}

.name-group .half-width:last-child :deep(.el-form-item__label) {
  width: 120px !important;
}

:deep(.name-input .el-input__wrapper) {
  width: 100%;
}

/* 地址相关输入框 */
:deep(.address-input .el-input__wrapper) {
  width: 100%;
}

:deep(.zip-input .el-input__wrapper) {
  width: 250px;
}

:deep(.prefecture-input .el-input__wrapper) {
  width: 250px;
}

/* 公司名称输入框样式 */
:deep(.company-input .el-input__wrapper) {
  width: 150%;
}

.company-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
  align-items: flex-start;
}

.company-group .half-width {
  flex: 1;
}

.company-group :deep(.el-form-item__label) {
  width: 180px !important;
  min-width: 80px;
}

.company-group :deep(.el-form-item__content) {
  margin-left: 0 !important;
}

.company-group :deep(.el-input__wrapper) {
  width: 200px !important;
}

.checkbox-container {
  font-size: 14px;
  margin-left: 180px;
}

.button-container {
  margin-left: 180px;
}

.register-button {
  height: 45px;
  font-size: 16px;
  border-radius: 6px;
}

.register-options {
  text-align: center;
  margin-top: 20px;
}

.login-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
}

.login-link:hover {
  text-decoration: underline;
}

.terms-link {
  color: #409eff;
  /* text-decoration: none; */
}

.terms-link:hover {
  text-decoration: underline;
}

.input-with-tip {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.form-tip {
  display: block;
  margin-top: 1px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}
.form-desc{
    display: block;
    margin-top: 3px;
    font-size: 90%;
    color: #666;
}
.password-confirm-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  margin-top: 15px;
}
</style>